package cn.bdqn.pn.controller.user;

import cn.bdqn.pn.pojo.user.Admin;
import cn.bdqn.pn.service.user.AdminService;
import cn.bdqn.pn.utils.AddYear;
import cn.bdqn.pn.utils.GetMessage;
import cn.bdqn.pn.utils.ImageUtil;
import cn.bdqn.pn.utils.QueryUtil;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminService adminService;

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/backstageLogin",method = RequestMethod.POST)
    public Integer backstageLogin(String username, String password,String codes_text,HttpServletRequest request,Model model){
        Subject subject = SecurityUtils.getSubject();
        HttpSession session = request.getSession();
        String code= (String) session.getAttribute("imageCode");
        String codesText=codes_text.toLowerCase();
        if(!code.toLowerCase().equals(codesText)){
            return 0;
        }
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++信息"+username+"+++++++++++"+password);
        String pwd= QueryUtil.MD5(password);
        Admin admin=adminService.backstageLogin(username,pwd);
        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
        if(admin!=null){
            Date time=admin.getLastLoginTime();
            if(time!=null && !time.equals("")){
                subject.login(token);
                session.setAttribute("admin", admin);
                return 1;
            }
            try {
                sendMessage(admin.getAdminTel(),request);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 3;
        }
        return 2;
    }


    @ResponseBody
    @RequestMapping(value = "/addOneLoginSession",method = RequestMethod.POST)
    public Integer addOneLoginSession(String username, String password, HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        HttpSession session = request.getSession();
        String pwd= QueryUtil.MD5(password);
        Admin admin=adminService.backstageLogin(username,pwd);
        if(admin!=null){
            UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
            subject.login(token);
            session.setAttribute("admin", admin);
            return 1;
        }
        return 0;
        }

    //生成验证码图片
    @RequestMapping("/getValicode") //对应/user/valicode.do请求
    public void valicode(HttpServletResponse response,HttpSession session) throws Exception{
        Object[] objs = ImageUtil.createImage();
        session.setAttribute("imageCode",objs[0]);
        BufferedImage image = (BufferedImage) objs[1];
        //点击其他按键请求
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, "png", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 =  encoder.encodeBuffer(bytes);//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        response.getWriter().write(png_base64);
    }



    /**
     * 按照 admin 查询数据
     */
    @RequestMapping(value = "/getAdministrator_list")
    public String selectAdminInfo(Model model,Admin admin,
                                       @RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
                                       @RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize) throws ParseException {
        Page<Admin> page=adminService.selectAdminInfo(admin,pageNo,pageSize);
        if(admin.getLevel()!=null){
            model.addAttribute("level",admin.getLevel());
        }
       if(admin.getArea()!=null && admin.getArea()!=""){
           model.addAttribute("area",admin.getArea());
       }
        model.addAttribute("page",page);
        System.out.println(JSON.toJSONString(page,true));
        return "administrator_list";
    }

    /**
     * 查询账号是否重复
     */
    @ResponseBody
    @RequestMapping(value = "/findAdminByAccount")
    public Page<Admin> selectAdminInfo(String account,Integer pageNo,Integer pageSize){
        Admin admin=new Admin();
        admin.setAccount(account);
        return  adminService.selectAdminInfo(admin,pageNo,pageSize);
    }

    /**
     * 查询账号信息根据id
     */
    @ResponseBody
    @RequestMapping(value = "/findAdminByAdminId")
    public Page<Admin> selectAdminInfo(Integer adminId,Integer pageNo,Integer pageSize){
        Admin admin=new Admin();
        admin.setAdminId(adminId);
        return  adminService.selectAdminInfo(admin,pageNo,pageSize);
    }

    /**
     * 添加代理商
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addAdmin",method = RequestMethod.POST)
    public Integer addAdmin(String account,String adminPwd,String adminTel,Integer level,Date enterTime,Integer fatherId){
        Admin admin=new Admin();
        admin.setAccount(account);

        //加密
        String pwd= QueryUtil.MD5(adminPwd);
        admin.setAdminPwd(pwd);


        admin.setAdminTel(adminTel);
        admin.setLevel(level);
        Timestamp timestamp=new Timestamp(enterTime.getTime());
        admin.setEnterTime(timestamp);
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String sDate=dateFormat.format(enterTime.getTime());
        Date date=AddYear.getNextYear(sDate,1);
        Timestamp timestamp1=new Timestamp(date.getTime());
        admin.setDueTime(timestamp1);
        admin.setIsDel(0);
        admin.setFatherId(fatherId);
        Integer roleId=(level+1);
        admin.setRoleId(roleId);
        int num=0;
        try{
             num=adminService.addAdmin(admin);
        }catch (RuntimeException e){
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 删除代理商（修改代理商状态）
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delAdmin",method = RequestMethod.POST)
    public Integer  delAdmin(Integer adminId,Integer level){
        System.out.println("--------------------------------------------level:"+level);
        if(level==3){
            System.out.println("--------------------------------------------num:"+adminService.delAdmin(adminId));
            return adminService.delAdmin(adminId);
        }else{
            Admin admin=adminService.findInfoByFatherId(adminId);
            System.out.println("--------------------------------------------admin:"+admin);
            if(admin!=null){
                return 0;
            }
            return adminService.delAdmin(adminId);
        }
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     * @throws Exception
     */
    public void sendMessage(String phone,HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        String value = GetMessage.getResult(phone);
        session.setAttribute("valueCode",value);
        System.out.println("-----------------------------------验证码发送成功");
    }

    /**
     * 判断是否和发送的验证码相同
     * @param code
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/judgeCoed",method = RequestMethod.POST)
    public Integer judgeCoed(String code,HttpServletRequest request) throws  Exception{
        HttpSession session = request.getSession();
        String valueCode= (String) session.getAttribute("valueCode");
        System.out.println("----------------------------code:"+code);
        System.out.println("----------------------------valueCode:"+valueCode);
        if(code.equals(valueCode)){
            return 1;
        }
        return 0;
    }

    /**
     * 禁用代理商（修改代理商状态）
     * @param adminId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/isDisable",method = RequestMethod.POST)
    public Integer isDisable(Integer adminId){
        return adminService.isDisable(adminId);
    }
    /**
     * 启用代理商（修改代理商状态）
     * @param adminId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/isDisable1",method = RequestMethod.POST)
    public Integer isDisable1(Integer adminId){
        return adminService.isDisable(adminId);
    }

    /**
     * 修改Admin信息
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateinfo",method = RequestMethod.POST)
    public Integer updateinfo(Integer adminId,String area,String alipay,String weChat,String adminTel){
        Admin admin=new Admin();
        admin.setAdminId(adminId);
        admin.setArea(area);
        admin.setAlipay(alipay);
        admin.setWeChat(weChat);
        admin.setAdminTel(adminTel);
        return adminService.updateinfo(admin);
    }


    @RequestMapping(value = "/Tologin")
    public String DoLogin(String orderNum) {
        return "login";
    }

    @RequestMapping(value = "/shops_index")
    public String getShops_index(String status,Model model, HttpServletRequest request) {
        HttpSession session=request.getSession();
        Admin admin= (Admin) session.getAttribute("admin");
        model.addAttribute("stu",admin.getAdminId());
        model.addAttribute("status",status);
        return "shops_index";
    }


    @RequestMapping(value = "/admin")
    public String adminTwo() {
        return "administrator_list";
    }

    @RequestMapping("/doLogout")
    public String doLogout(HttpServletRequest request) {
        // 1、获取Subject
        Subject subject = SecurityUtils.getSubject();
        HttpSession session = request.getSession();
        // 2、执行注销
        try {
            subject.logout();
            session.removeAttribute("admin");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return "login";
        }
    }
}
